package xing.application.api;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import xing.domain.isv.suite.CorpSuiteAuth;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/*******************************************************************************************
 * 类描述：  
 *
 * @author: dustin
 * @date： 2017-8-22 14:41
 * @Description: token相关接口
 * @version 1.0.0
 *
 *
 * Version    Date       ModifiedBy                 Content  
 * -------- ---------    ----------         ------------------------  
 * 1.0.0     2017-8-22    Administrator                            
 *******************************************************************************************
 */
@Service
public class SuiteAuthApi {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
    * @Description: 获取套件访问Token
    * @param:  * @param null
    * @Author: dustin
    * @Date: 2017-8-22
    */
    public String getTicket(String suiteKey,String suiteSecret,String suiteTicket){
        try{
            Map<String,String> map=new HashMap<>();
            map.put("suite_key",suiteKey);
            map.put("suite_secret",suiteSecret);
            map.put("suite_ticket",suiteTicket);
            String res = Client.postCommand("service/get_suite_token",map,null);

            ObjectMapper mapper = new ObjectMapper();
            JsonNode json = mapper.readTree(res);
            if(json.get("errcode").asInt()==0)
                return json.get("suite_access_token").asText();
            else{
                throw new Exception(res);
            }
        }catch (Exception e){
            logger.error("获取suite_access_token失败:{}",e.getMessage());
            return null;
        }
    }

    /**
    * @Description: 获取永久授权码
    * @param:  * @param null
    * @Author: dustin
    * @Date: 2017-8-22
    */
    public CorpSuiteAuth getPermanentCode(String suiteKey, String tmpAuthCode, String suiteAccessToken) {
        try{
            Map<String,String> para=new HashMap<>();
            para.put("tmp_auth_code", tmpAuthCode);
            String cmd="service/get_permanent_code?suite_access_token=" + suiteAccessToken;
            String res = Client.postCommand(cmd,para,null);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode json = mapper.readTree(res);
            if(json.get("errcode").asInt()==0){
                JsonNode authInfo=json.path("auth_corp_info");
                String chPcode = StringUtils.isEmpty(json.get("ch_permanent_code"))?"":json.get("ch_permanent_code").asText();
                String pCode = StringUtils.isEmpty(json.get("permanent_code"))?"":json.get("permanent_code").asText();
                String corpId = authInfo.get("corpid").asText();
                CorpSuiteAuth corpSuiteAuth = new CorpSuiteAuth();
                corpSuiteAuth.setSuiteKey(suiteKey);
                corpSuiteAuth.setChPermanentCode(chPcode);
                corpSuiteAuth.setPermanentCode(pCode);
                corpSuiteAuth.setCorpId(corpId);
                return corpSuiteAuth;
            }
            else{
                throw new Exception(res);
            }

        }catch(Exception e){
            logger.error("获取永久授权码失败:{}",e.getMessage());
            return null;
        }

    }

    /**
    * @Description: 激活授权套件
    * @param:  * @param null
    * @Author: dustin
    * @Date: 2017-8-23
    */
    public void activateSuite(String suiteToken, String suiteKey, String authCorpId, String permanentCode) {
        try{
            Map<String,String> para=new HashMap<>();
            para.put("suite_key", suiteKey);
            para.put("auth_corpid", authCorpId);
            para.put("permanent_code", permanentCode);

            String cmd="service/activate_suite?suite_access_token=" + suiteToken;
            String res = Client.postCommand(cmd,para,null);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode json = mapper.readTree(res);
            if(json.get("errcode").asInt()==0){
                logger.info("激活授权套件成功，corpId:{}",authCorpId);
            }
            else{
                logger.info("激活授权套件失败，corpId:{}",authCorpId);
                throw new Exception(res);
            }

        }catch(Exception e){
            logger.error("激活授权套件异常，corpId:{} error:{}",authCorpId, e.getMessage());
        }

    }

}
